/**
 * Copyright (C) 2015-2018 IQIYI
 * All rights reserved.
 *
 * AUTHOR(S)
 * 王海斌
 *   E-mail: wanghaibin@qiyi.com
 *
 * VERSION
 *   Tue 03 Jul 2018 11:02:00 AM CST
 */

/* localtime example */
#include <stdio.h>
#include <time.h>
#include <string>
#include <string.h>
#include <sys/time.h>

// 将格式化strLocalTime字符串转为struct tm格式
void printLocalTime(const std::string &strLocalTime)
{
    struct tm newTime;
    memset(&newTime, 0, sizeof(struct tm));
    //strptime(curTime.c_str(),"%a %b %d %H:%M:%S %Y", &newTime); //Mon Nov 12 18:31:01 2001
    strptime(strLocalTime.c_str(),"%c", &newTime);
    long long ltime=mktime(&newTime);
    printf("local time: %s ,, unix date=%lld\n",strLocalTime.c_str(), ltime);
}

// 将格式化GMT格式字符串转为tm格式
void printGMTTime(const std::string &gmtTime)
{
    struct tm newTime;
    memset(&newTime, 0, sizeof(struct tm));
    strptime(gmtTime.c_str(),"%a, %d %b %Y %T %Z", &newTime);
    char newTimeStr[128]={0};
    strftime(newTimeStr, sizeof(newTimeStr),"%a, %d %b %Y %H:%M:%S %Z", &newTime);
    printf("GMT Time \"%s\" to unix = %lld,, rechage=%s, str=%s\n", gmtTime.c_str(), mktime(&newTime), asctime(&newTime), newTimeStr);
}

int main ()
{
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    std::string curTime=asctime (timeinfo);
    printf ( "Current local time and date: %s\n", curTime.c_str());
    printLocalTime(curTime);

    printLocalTime("Fri Jun 22 1:0:1 2018");

    printLocalTime("Mon, 16 Oct 2017 07:36:27 GMT");
    printGMTTime("Mon, 16 Oct 2017 07:36:27 GMT");


    time_t curTime2 = time(NULL);
    char newTimeStr[128]={0};
    strftime(newTimeStr, sizeof(newTimeStr),"%a, %d %b %Y %H:%M:%S %Z", gmtime(&curTime2));
    printf("\ncurrent tm=%lld, %s\n", curTime2, newTimeStr);
    return 0;
}


